package com.tronsis.distribution.activity.me.upgrade;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;

import com.tronsis.distribution.R;
import com.tronsis.distribution.bean.UpgradeBean;
import com.tronsis.distribution.bean.UserBean;
import com.tronsis.distribution.biz.factory.UpgradeBizFactory;
import com.tronsis.distribution.biz.factory.UserBizFactory;
import com.tronsis.distribution.util.CommonUtil;
import com.tronsis.distribution.util.StateUtil;
import com.tronsis.library.activity.ToolBarBaseActivity;
import com.tronsis.library.adapter.recyclerview.CommonAdapter;
import com.tronsis.library.adapter.recyclerview.MultiItemTypeAdapter;
import com.tronsis.library.adapter.recyclerview.base.ViewHolder;
import com.tronsis.library.adapter.recyclerview.wrapper.LoadMoreWrapper;
import com.tronsis.library.http.ListBean;
import com.tronsis.library.http.UICallBack;
import com.tronsis.library.util.DateUtil;
import com.tronsis.library.util.DisplayUtil;
import com.tronsis.library.util.StringUtil;
import com.tronsis.library.util.ToastUtil;
import com.tronsis.library.widget.ConfirmDialog;
import com.tronsis.library.widget.MyDecoration;
import com.tronsis.library.widget.RecycleViewDivider;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 升/降级申请
 */
public class LevelApplyActivity extends ToolBarBaseActivity {

    @BindView(R.id.rv_level_apply)
    RecyclerView mRv;
    @BindView(R.id.btn_apply)
    Button mBtnApply;


    private List<UpgradeBean> mDataList = new ArrayList<>();
    private int mPage = 1;
    private int mSize = 15;
    private int mTotal;
    private LoadMoreWrapper mLoadMoreWrapper;
    private UserBean mLoginUserBean = UserBizFactory.createBiz().getLoginUser(this);
    private String mIntentType;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_level_apply);
        ButterKnife.bind(this);
        setTitle(true, getString(R.string.apply));
        mIntentType = getIntent().getType();
        initRv();
        getUpgrades(mPage, mSize, true);
        httpGetUserInfo();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            getUpgrades(mPage, mSize, true);
        }
    }

    private void initRv() {
        CommonAdapter<UpgradeBean> adapter = new CommonAdapter<UpgradeBean>(mContext, mDataList, R.layout.item_level_apply) {
            @Override
            protected void convert(ViewHolder holder, final UpgradeBean upgradeBean, final int position) {
                holder.setText(R.id.tv_state, StateUtil.getUpgradeApplyState(mContext, upgradeBean.getState()));
                holder.setText(R.id.tv_time, DateUtil.getDateTimeString(upgradeBean.getCreatedOn()));
                holder.setText(R.id.tv_order_code, getString(R.string.format_upgrade_order_no, upgradeBean.getCode()));
                holder.setText(R.id.tv_type, getString(R.string.format_upgrade_type, StateUtil.getUpgradeType(mContext, upgradeBean.getType())));
                holder.setText(R.id.tv_level, getString(R.string.format_upgrade_level, StateUtil.getLevelText(upgradeBean.getToLevel())));
                holder.setText(R.id.tv_region, getString(R.string.format_upgrade_region, CommonUtil.getRegionString(upgradeBean.getToRegion())));

                if (StringUtil.isEquals(upgradeBean.getState(), StateUtil.UPGRADE_PAY)) {
                    holder.setVisible(R.id.ll_btn, true);
//                    holder.setVisible(R.id.btn_delete, true);
//                    holder.setVisible(R.id.btn_pay, true);
                } else {
                    holder.setVisible(R.id.ll_btn, false);
//                    holder.setVisible(R.id.btn_delete, false);
//                    holder.setVisible(R.id.btn_pay, false);
                }

                if (StringUtil.isEquals(StateUtil.TO_AGENT, upgradeBean.getType())) {
                    holder.setVisible(R.id.tv_type, false);
                } else {
                    holder.setVisible(R.id.tv_type, true);
                }

                final String upgradeId = upgradeBean.getId();
                holder.setOnClickListener(R.id.btn_delete, new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        new ConfirmDialog(mContext, new ConfirmDialog.OnBottomButtonClickListener() {
                            @Override
                            public void onLeftButtonClick(View view) {
                            }

                            @Override
                            public void onRightButtonClick(View view) {
                                deleteUpgrade(upgradeId);
                            }
                        }).showDialog("确认删除？", "取消", "确定");
                    }
                });

                holder.setOnClickListener(R.id.btn_pay, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(mContext, LevelApplyDetailActivity.class);
                        intent.putExtra("UpgradeBean", upgradeBean);
                        startActivityForResult(intent, 127);
                    }
                });

            }


        };

        adapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                Intent intent = new Intent(mContext, LevelApplyDetailActivity.class);
                intent.putExtra("UpgradeBean", mDataList.get(position));
                startActivityForResult(intent, 141);
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });

        mLoadMoreWrapper = new LoadMoreWrapper(adapter);
        mLoadMoreWrapper.setLoadMoreView(R.layout.rv_load_more);
        mLoadMoreWrapper.setOnLoadMoreListener(new LoadMoreWrapper.OnLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                if (mDataList.size() % 15 == 0 && mDataList.size() > 0 && mDataList.size() < mTotal) {
                    mPage = (mDataList.size() / 15) + 1;
                    getUpgrades(mPage, mSize, false);
                }
            }
        });

        int height = DisplayUtil.getInstance(mContext).dp2px(14);
        int color = Color.parseColor("#F4F4F4");
        RecycleViewDivider decoration = new RecycleViewDivider(mContext, MyDecoration.VERTICAL_LIST, height, color);
        mRv.addItemDecoration(decoration);
        mRv.setLayoutManager(new LinearLayoutManager(mContext));
        mRv.setAdapter(mLoadMoreWrapper);
    }

    @OnClick(R.id.btn_apply)
    void applyClick() {
        if (StringUtil.isEquals(mIntentType, "level") && StringUtil.isEquals(mLoginUserBean.getRole(), StateUtil.ROLE_UO_AGENT) && StringUtil.isEquals(mLoginUserBean.getLevel(), "D")) {
            ToastUtil.showMessage(mContext, "当前为准代理D级，不能进行申请");
            return;
        }
        if (StringUtil.isEquals(mIntentType, "switch") && mDataList.size() > 0) {
            ToastUtil.showToastInCenter(mContext, "转代理已申请");
            return;
        }
        Intent intent = new Intent(mContext, LevelApplySubmitActivity.class);
        intent.setType(mIntentType);
        startActivityForResult(intent, 100);
    }

    private void deleteUpgrade(String upgradeId) {
        // FIXME: 2019/4/14 客户端错误
        try {

            UpgradeBizFactory.createBiz().deleteUpgrade(this, upgradeId, new UICallBack() {
                @Override
                public void onStart() {
                    showLoadingDialog();
                }

                @Override
                public void onRefresh(Object data) {
                    dismissLoadingDialog();
                    getUpgrades(mPage, mSize, true);
                }

                @Override
                public void onFailure(int status) {
                    dismissLoadingDialog();

                }
            });
        } catch (Exception e) {
            dismissLoadingDialog();
            e.printStackTrace();
        }
    }

    private void getUpgrades(int page, int size, final boolean isRefresh) {
        try {

            UpgradeBizFactory.createBiz().getUpgrades(this, page, size, new UICallBack() {
                @Override
                public void onStart() {
                    showLoadingDialog();
                }

                @Override
                public void onRefresh(Object data) {
                    dismissLoadingDialog();
                    ListBean listBean = (ListBean) data;
                    mTotal = listBean.getTotal();
                    List<UpgradeBean> list = listBean.getList();
                    if (isRefresh) {
                        mDataList.clear();
                    }
                    for (UpgradeBean upgradeBean : list) {
                        if (StringUtil.isEquals(mIntentType, "switch")) {
                            if (StringUtil.isEquals(StateUtil.TO_AGENT, upgradeBean.getType())) {
                                mDataList.add(upgradeBean);
                            }
                        } else {
                            if (!StringUtil.isEquals(StateUtil.TO_AGENT, upgradeBean.getType())) {
                                mDataList.add(upgradeBean);
                            }
                        }

                    }
                    mLoadMoreWrapper.notifyDataSetChanged();
                }

                @Override
                public void onFailure(int status) {
                    dismissLoadingDialog();

                }
            });
        } catch (Exception e) {
            dismissLoadingDialog();
            e.printStackTrace();
        }
    }


    private void httpGetUserInfo() {
        try {
            UserBizFactory.createBiz().getUserInfo(this, new UICallBack() {
                @Override
                public void onStart() {

                }

                @Override
                public void onRefresh(Object data) {
                    UserBean bean = (UserBean) data;
                    if (data != null) {
                        mLoginUserBean = bean;
                    }
                }

                @Override
                public void onFailure(int status) {

                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
